package com.base.po.czb_sdk;

import com.base.utils.MD5Util;
import com.base.utils.Md5Encrypt;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class CZBUtil {

    /**
     * 参数拼接
     */
    public static String getParam(Map<String, Object> paramsMap, String sign) {
        // 返回拼接参数
        String param = "";

        try {
            List<String> params = new ArrayList<>();
            for (String key : paramsMap.keySet()) {
                String values = key + "=" + paramsMap.get(key);
                params.add(values);
            }
            for (int i = 0; i < params.size(); i++) {
                if (i == 0) {
                    param += params.get(i);
                } else {
                    param += "&" + params.get(i);
                }
            }
            // 参数不为空 拼接sign
            if (param != null && !param.equals("") && sign != null && !sign.equals("")) {
                param += "&sign=" + sign;
            }
        } catch (Exception e) {
            System.out.println("车主邦API参数拼接失败");
        }

        return param;
    }

    public static String getSign(Map<String, Object> paramsMap, String appSecret) {
        // 返回MD5签名
        String sign = "";

        try {
            List<String> params = new ArrayList<>();
            for (String key : paramsMap.keySet()) {
                String values = key + paramsMap.get(key);
                params.add(values);
            }
            if (params != null && params.size() > 0) {
                //String.CASE_INSENSITIVE_ORDER A在 a 前面
                Collections.sort(params, String.CASE_INSENSITIVE_ORDER);
                // 获取拼接参数
                String param = "";
                for (int i = 0; i < params.size(); i++) {
                    param += params.get(i);
                }
                // 参数不为空 拼接key
                if (param != null && !param.equals("")) {
                    param = appSecret + param + appSecret;
                }
                sign = Md5Encrypt.encrypt32(param);
            }
        } catch (Exception e) {
            System.out.println("API签名生成失败");
        }
        return sign;
    }

    public static String getSign(String characterEncoding, SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        sbkey = sbkey.append("key=" + key);
        System.out.println("加密前的参数:" + sbkey);
        //MD5加密,结果转换为大写字符
        String sign = MD5Util.MD5Encode(sbkey.toString(), characterEncoding).toUpperCase();
        System.out.println("sign:" + sign);
        return sign;
    }

    public static String getSignlow(String characterEncoding, SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        sbkey = sbkey.append("key=" + key);
        //MD5加密,结果转换为大写字符
        String sign = MD5Util.MD5Encode(sbkey.toString(), characterEncoding).toLowerCase();
        return sign;
    }

    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        //System.out.println("字符串:"+sb.toString());
        sbkey = sbkey.append("key=" + key);
        //MD5加密,结果转换为大写字符
        System.out.println("加密前的参数:" + sbkey);
        String sign = MD5Util.MD5Encode(sbkey.toString(), characterEncoding).toUpperCase();
        System.out.println("加密的sign:" + sign);
        return sb.toString() + "sign=" + sign;
    }

    public static SortedMap<Object, Object> getRequestParameters(HttpServletRequest request) {
        String parameters = "";//请求参数
        if ("GET".equals(request.getMethod())) {//GET请求时的参数
            String urlParameter = request.getQueryString();//网址中的参数
            if (urlParameter != null && !"".equals(urlParameter)) {
                try {
                    urlParameter = URLDecoder.decode(urlParameter, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                urlParameter = "";
            }
            parameters = urlParameter;
        } else if ("POST".equals(request.getMethod())) {//POST请求时的参数
            String totalParameter = "";//表单及网址中全部参数
            Map<String, String[]> params = request.getParameterMap();
            int parametersNum = request.getParameterMap().size();//参数个数
            int flag = 1;
            for (String key : params.keySet()) {

                String[] values = params.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value = values[i];
                    totalParameter += key + "=" + value;
                }
                if (flag < parametersNum) {
                    totalParameter += "&";
                }
                flag += 1;
            }
            parameters = totalParameter;
        }
//        Map<String, Object> map=new HashMap<String, Object>();
        SortedMap<Object, Object> map1 = new TreeMap<Object, Object>();
        String[] arr = parameters.split("&");
        for (int i = 0; i < arr.length; i++) {
            String key = arr[i].substring(0, arr[i].indexOf("="));
            String value = arr[i].substring(arr[i].indexOf("=") + 1);
//            map.put(key, value);
            map1.put(key, value);
        }
        return map1;
    }

}
